/*
 * @Author: zxc
 * @Date: 2020-10-21 11:40:04
 * @LastEditTime: 2020-10-21 17:46:42
 * @LastEditors: zxc
 * @Description:
 */
const Ajv = require("ajv")
const locallize = require("ajv-i18n")
// or ESM/TypeScript import
const schema = {
  type: "object",
  properties: {
    name: {
      type: "string",
      // test: 'tses',
      errorMessage: {
        type: '这他喵是错的哦~',
        minLength: '长度不能小于xx字符'
      },
      minLength: 19
      // format: 'email',
    },
    age: {
      type: "number"
    },
    pets: {
      type: "array",
      // items: {
      //   type: 'string'
      // }
      items: [{
          type: "string"
        },
        {
          type: "number"
        }
      ]
    },
    isWorker: {
      type: "boolean"
    }
  },
  required: ["name", "age", "pets"]
}

const ajv = new Ajv({
  allErrors: true,
  jsonPointers: true
}) // options can be passed, e.g. {allErrors: true}
require('ajv-errors')(ajv)
ajv.addKeyword('test', {

  macro(schema, parentSChema) {
    console.log(schema, parentSChema)
    return {
      minLength: 17
    };
  },

  // compile(schema, parentSChema) {
  //   console.log(schema, parentSChema)
  //   return () => true
  // },
  // metaSchema: {
  //   type: 'string'
  // }
  // validate: function fun(schema, data) {
  //   // console.log(schema, data)
  //   if (schema === true) return true
  //   else if (schema.length === 6) return true
  //   else {
  //     fun.errors = [{
  //       keyword: 'test',
  //       dataPath: '.name',
  //       schemaPath: '#/properties/name/test',
  //       params: {
  //         keyword: 'test'
  //       },
  //       message: 'hello,带傻逼'
  //     }]
  //     return false
  //   }
  // return false
  // }
})
const validate = ajv.compile(schema)
const obj = {
  name: "zxc@gmail.com",
  age: 23,
  pets: ["dog", 12],
  isWorker: true
}
const valid = validate(obj)
if (!valid) {
  locallize.zh(validate.errors)
  console.log(validate.errors)
}